package server.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import plug.result.ReqPage;
import plug.result.RetResponse;
import plug.result.RetResult;
import server.dao.OrderSpackDao;
import server.dao.ShopDao;
import server.dao.ShopOrderDao;
import server.dao.UserBlanceDao;
import server.model.entity.*;
import server.service.OrderService;

import java.util.List;
import java.util.Optional;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@RestController
@RequestMapping("v1/api/shopOrder")
@CrossOrigin(origins = "*")
public class ShopOrderController {
    @Autowired
    ShopOrderDao shopOrderDao;
    @Autowired
    OrderService orderService;
    @Autowired
    UserBlanceDao userBlanceDao;
    @Autowired
    OrderSpackDao orderSpackDao;

    @PostMapping("/all")
    public RetResult all(@RequestBody ReqPage reqPage) {
        JSONObject req = Optional.ofNullable(reqPage.getCommon()).orElseGet(JSONObject::new);
        ShopOrder entity = JSON.parseObject(req.toJSONString(), ShopOrder.class);
        int page = reqPage.getPage() - 1;
        int size = reqPage.getLimit();
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "modifiedTime");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("users.name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<ShopOrder> example = Example.of(entity, matcher);
        Page<ShopOrder> pages = shopOrderDao.findAll(example, pageable);
        List<ShopOrder> pageList = pages.getContent();
        return RetResponse.makeRsp(0, "成功", pageList, (int) pages.getTotalElements());
    }

    @PostMapping("/spack/all")
    public RetResult spackAll(@RequestBody ReqPage reqPage) {
        JSONObject req = Optional.ofNullable(reqPage.getCommon()).orElseGet(JSONObject::new);
        OrderSpack entity = JSON.parseObject(req.toJSONString(), OrderSpack.class);
        int page = reqPage.getPage() - 1;
        int size = reqPage.getLimit();
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "modifiedTime");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("users.name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<OrderSpack> example = Example.of(entity, matcher);
        Page<OrderSpack> pages = orderSpackDao.findAll(example, pageable);
        List<OrderSpack> pageList = pages.getContent();
        return RetResponse.makeRsp(0, "成功", pageList, (int) pages.getTotalElements());
    }

    @PutMapping("/status/{id}")
    public RetResult putStatus(@PathVariable String id, @RequestBody ShopOrder.Status status) {
        ShopOrder shopOrder = shopOrderDao.findById(id).get();
        if (status.getNumber() > shopOrder.getStatus().getNumber()) {
            if (status.getNumber() == 5 && shopOrder.getStatus().getNumber() > 1) {
                return RetResponse.makeErrRsp("已付款不允许取消！");
            }
            if (status.getNumber() == 5) {
                UserBlance ub = userBlanceDao.findByTypeAndUserId(UserBlance.Type.RMB, shopOrder.getUsers().getId());
                ub.setFrostMoney(ub.getFrostMoney().subtract(shopOrder.getAnnul()));
                ub.setMoney(ub.getMoney().add(shopOrder.getAnnul()));
                userBlanceDao.save(ub);
            }
            if (status.getNumber() == 3 && shopOrder.getStatus().getNumber() != 2) {
                return RetResponse.makeErrRsp("状态不允许操作");
            }
            shopOrder.setStatus(status);
            shopOrderDao.save(shopOrder);
            if (status.equals(ShopOrder.Status.YES)) {
                OrderSpack orderSpack = orderSpackDao.findByShopOrder_Id(shopOrder.getId());
                if (orderSpack != null) {
                    orderSpack.setStatus(true);
                    orderSpackDao.save(orderSpack);
                }
                orderService.payOrder(shopOrder);
            }
        } else {
            return RetResponse.makeErrRsp("状态不允许操作");
        }
        return RetResponse.makeOKRsp();
    }
}
